package com.you.atlas.web.place.module.action;

import java.io.IOException;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.you.atlas.biz.place.service.PhotoService;
import com.you.atlas.biz.place.vo.PhotoAddVO;
import com.you.common.file.ImageService;
import com.you.common.result.ServiceResult;
import com.you.common.webx.AuthContext;

public class PhotoAction {

    @Autowired
    private PhotoService  photoService;

    @Autowired
    private ImageService imageService;

    public void doUpload(@FormGroup("uploadImg") Group group,  @Param("placeId") Long placeId,Context context,Navigator navigator) {
        FileItem fileItem = group.getField("imgUrl").getFileItem();
        if (fileItem != null) {
            try {
                String imgUrl = imageService.scaleImg(fileItem.getInputStream(), fileItem.getName(), 600, 450);
                String thumbImgUrl = imageService.scaleImg(imgUrl, 170, 280);
                context.put("imgUrl", imgUrl);
                context.put("thumbImgUrl", thumbImgUrl);
                context.put("placeId", placeId);
                navigator.forwardTo("photoAdd.vm");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void doAdd(@FormGroup("addPhoto") Group group, @Param("albumId") Long albumId,
                      @Param("placeId") Long placeId, Context context, Navigator navigator) {
        Long memberId = AuthContext.getContext().getMemberId();
        PhotoAddVO photoAddVO = new PhotoAddVO();
        group.setProperties(photoAddVO);
        photoAddVO.setMemberId(memberId);
        photoAddVO.setAlbumId(albumId);
        photoAddVO.setPlaceId(placeId);
        ServiceResult<Object> result = photoService.addPhoto(photoAddVO);

        if (result.isSuccess()) {
            navigator.redirectTo("placeModule").withTarget("photoView.vm").withParameter("id", result.getModule().toString());
        }

    }
}
